import base64
import pickle

from django_redis import get_redis_connection


def merge_cookie_to_redis(request, response):
    # 读取COOKIE
    cookie_carts = request.COOKIES.get('carts')
    # 判断是否存在
    if cookie_carts:
        # 解码
        carts = pickle.loads(base64.b64decode(cookie_carts))

        cookie_dict = {}
        selected_ids = []
        unselected_ids = []

        # redis中的数据
        # redis_cli.hincrby('carts_%s' % user.id, sku_id, count)
        # 默认选中，存储在集合
        # redis_cli.sadd('selected_s' % user.id, sku_id)
        for sku_id, count_selected_dict in carts.items():
            # 1: {count:666,selected:True},
            # 字典数据
            cookie_dict[sku_id] = count_selected_dict['count']
            if count_selected_dict['selected']:
                selected_ids.append(sku_id)
            else:
                unselected_ids.append(sku_id)
        user = request.user
        # 4. 将字典数据，列表数据分别添加到redis中
        redis_cli = get_redis_connection('carts')
        pipeline = redis_cli.pipeline()
        #  {sku_id:count,sku_id:count,....}
        pipeline.hmset('carts_%s' % user.id, cookie_dict)
        # selected_id [1,3,2]
        if len(selected_ids) > 0:
            # *selected_ids  对列表数据进行解包
            pipeline.sadd('selected_%s' % user.id, *selected_ids)
        # unselected_id [4,5,6]
        if len(unselected_ids) > 0:
            pipeline.srem('selected_%s' % user.id, *unselected_ids)

        pipeline.execute()

        # 5. 删除cookie数据
        response.delete_cookie('carts')

        # response 最好返回
    return response
